/*
 * @Date         : 2024-05-20 14:13:12 星期1
 * @Author       : xut
 * @Description  :
 */
import type { Request, Response } from "express"
import grpc from "@grpc/grpc-js"
import { userClient } from "../client"
import {
  GetUserPageInput,
  GetUserInput,
  UpdateUserInput,
  DeleteUserInput,
} from "../schema/user.schema"
import { User } from "../../pb/user/User"

export async function getUsersPage(
  req: Request<{}, {}, {}, GetUserPageInput>,
  res: Response
) {
  const headerMetadata = new grpc.Metadata()
  headerMetadata.set("user", JSON.stringify(req.user))

  const { pageNo, pageSize } = req.query
  const stream = userClient.listUsers(
    {
      page_no: pageNo,
      page_size: parseInt(pageSize),
    },
    headerMetadata
  )

  const userList: User[] = []
  stream.on("data", (data: User) => {
    userList.push(data)
  })
  stream.on("end", () => {
    return res.status(200).json({ status: "success", list: userList })
  })
  stream.on("error", (err: any) => {
    res.status(500).json({
      status: "error",
      message: err.message,
    })
  })
}
export async function getUser(req: Request<GetUserInput>, res: Response) {
  const headerMetadata = new grpc.Metadata()
  headerMetadata.set("user", JSON.stringify(req.user))

  const id = req.params.id

  userClient.getUser({ id }, headerMetadata, (err, data) => {
    if (err) {
      return res.status(400).json({
        status: "fail",
        message: err.message,
      })
    }

    return res.status(200).json(data)
  })
}

export async function updateUser(
  req: Request<UpdateUserInput["params"], {}, UpdateUserInput["body"]>,
  res: Response
) {
  const headerMetadata = new grpc.Metadata()
  headerMetadata.set("user", JSON.stringify(req.user))

  const id = req.params.id
  const { name, photo } = req.body

  userClient.updateUser({ id, name, photo }, headerMetadata, (err, data) => {
    if (err) {
      return res.status(400).json({
        status: "fail",
        message: err.message,
      })
    }
    return res.status(200).json(data)
  })
}

export async function deleteUser(req: Request<DeleteUserInput>, res: Response) {
  const headerMetadata = new grpc.Metadata()
  headerMetadata.set("user", JSON.stringify(req.user))

  const id = req.params.id
  userClient.deleteUser({ id }, headerMetadata, (err, data) => {
    if (err) {
      return res.status(400).json({
        status: "fail",
        message: err.message,
      })
    }

    return res.status(200).json(data)
  })
}
